require.config({
    paths: {
        'fastim': '../addons/fastim/js/fastim'
    },
    shim: {
        'fastim': {
            deps: ['css!../addons/fastim/css/fastim_default.css'],
            exports: 'FastIm'
        }
    }
});

define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'fastim'], function ($, undefined, Backend, Table, Form, FastIm) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'fastim/groupchat/index' + location.search,
                    add_url: 'fastim/groupchat/add',
                    edit_url: 'fastim/groupchat/edit',
                    del_url: 'fastim/groupchat/del',
                    multi_url: 'fastim/groupchat/multi',
                    import_url: 'fastim/groupchat/import',
                    record_url: 'fastim/groupchat/record',
                    users_url: 'fastim/groupchat/users',
                    table: 'fastim_group_chat',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        // {field: 'leader', title: __('Leader')},
                        {field: 'nickname', title: __('Nickname'), operate: 'LIKE'},
                        {
                            field: 'avatar',
                            title: __('Avatar'),
                            operate: false,
                            events: Table.api.events.image,
                            formatter: Table.api.formatter.image,
                            visible: false
                        },
                        {field: 'fastimuser.nickname', title: __('Leader'), operate: false},
                        {field: 'leader', title: __('Leader') + 'ID', visible: false, placeholder: 'IM用户ID'},
                        // {field: 'bio', title: __('Bio'), operate: 'LIKE'},
                        {field: 'user_count', title: __('当前人数')},
                        {field: 'num', title: __('虚拟人数')},
                        {field: 'max_user_count', title: __('Max_user_count')},
                        {field: 'status', title: __('Status'), formatter: Table.api.formatter.status, searchList: {0: __('Status 0'), 1: __('Status 1'), 2: __('Status 2')}},
                        {
                            field: 'add_mode',
                            title: __('Add_mode'),
                            searchList: {"0": __('Add_mode 0'), "1": __('Add_mode 1')},
                            formatter: Table.api.formatter.normal
                        },
                        {
                            field: 'invite_join_group',
                            title: __('Invite_join_group'),
                            searchList: {"0": __('Invite_join_group 0'), "1": __('Invite_join_group 1')},
                            formatter: Table.api.formatter.normal
                        },
                        {
                            field: 'speak',
                            title: __('Speak'),
                            searchList: {"0": __('Speak 0'), "1": __('Speak 1')},
                            formatter: Table.api.formatter.normal
                        },
                        {
                            field: 'history_message',
                            title: __('History_message'),
                            searchList: {"0": __('History_message 0'), "1": __('History_message 1')},
                            formatter: Table.api.formatter.normal
                        },
                        {
                            field: 'createtime',
                            title: __('Createtime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate,
                            buttons: [
                                {
                                    name: 'record',
                                    title: '沟通记录',
                                    classname: 'btn btn-xs btn-info btn-dialog',
                                    icon: 'fa fa-file-text-o',
                                    url: $.fn.bootstrapTable.defaults.extend.record_url,
                                },
                                {
                                    name: 'users',
                                    title: '成员列表',
                                    classname: 'btn btn-xs btn-warning btn-dialog',
                                    icon: 'fa fa-address-book',
                                    url: $.fn.bootstrapTable.defaults.extend.users_url,
                                }
                            ]
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    dragsort_url: '',
                    record_url: 'fastim/groupchat/record',
                    users_url: 'fastim/groupchat/users'
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'fastim/groupchat/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        // {field: 'leader', title: __('Leader')},
                        {field: 'nickname', title: __('Nickname'), operate: 'LIKE'},
                        {
                            field: 'avatar',
                            title: __('Avatar'),
                            operate: false,
                            events: Table.api.events.image,
                            formatter: Table.api.formatter.image,
                            visible: false
                        },
                        {field: 'fastimuser.nickname', title: __('Leader'), operate: false},
                        {field: 'leader', title: __('Leader') + 'ID', visible: false, placeholder: 'IM用户ID'},
                        // {field: 'bio', title: __('Bio'), operate: 'LIKE'},
                        {field: 'user_count', title: __('当前人数'), visible: false},
                        {field: 'num', title: __('虚拟人数'), visible: false},
                        {field: 'max_user_count', title: __('Max_user_count'), visible: false},
                        {field: 'status', title: __('Status'), visible: false, formatter: Table.api.formatter.status, searchList: {0: __('Status 0'), 1: __('Status 1'), 2: __('Status 2')}},
                        {
                            field: 'add_mode',
                            title: __('Add_mode'),
                            searchList: {"0": __('Add_mode 0'), "1": __('Add_mode 1')},
                            formatter: Table.api.formatter.normal,
                            visible: false
                        },
                        {
                            field: 'invite_join_group',
                            title: __('Invite_join_group'),
                            searchList: {"0": __('Invite_join_group 0'), "1": __('Invite_join_group 1')},
                            formatter: Table.api.formatter.normal,
                            visible: false
                        },
                        {
                            field: 'speak',
                            title: __('Speak'),
                            searchList: {"0": __('Speak 0'), "1": __('Speak 1')},
                            formatter: Table.api.formatter.normal,
                            visible: false
                        },
                        {
                            field: 'history_message',
                            title: __('History_message'),
                            searchList: {"0": __('History_message 0'), "1": __('History_message 1')},
                            formatter: Table.api.formatter.normal,
                            visible: false
                        },
                        {
                            field: 'createtime',
                            title: __('Createtime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            width: '200px',
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'record',
                                    title: '沟通记录',
                                    classname: 'btn btn-xs btn-info btn-dialog',
                                    icon: 'fa fa-file-text-o',
                                    url: $.fn.bootstrapTable.defaults.extend.record_url,
                                },
                                {
                                    name: 'users',
                                    title: '成员列表',
                                    classname: 'btn btn-xs btn-warning btn-dialog',
                                    icon: 'fa fa-address-book',
                                    url: $.fn.bootstrapTable.defaults.extend.users_url,
                                },
                                {
                                    name: 'Restore',
                                    title: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'fastim/groupchat/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    title: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'fastim/groupchat/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        users: function () {
            Controller.api.bindevent();
        },
        record: function () {
            $('.chat-records').hide();

            FastIm.config = {__CDN__: Config.pageData.__CDN__}
            FastIm.userinfo = {
                id: Config.sessionInfo.user.id
            }

            Controller.api.renderRecord(Config.message, Config.sessionInfo, Config.pageData)

            $(document).on('scroll', function (event) {
                var e = $(event.target);

                if (!Config.pageData.nextpage) {
                    return false;
                }

                if (e.find('.chat-records')) {
                    var scrollTop = e.scrollTop(), elHeight = e[0].body.clientHeight, contentH = e[0].body.scrollHeight
                    if (scrollTop == (contentH - elHeight)) {
                        Fast.api.ajax({
                            url: 'fastim/groupchat/record/ids/' + Config.sessionInfo.chat_id + '/page/' + (parseInt(Config.pageData.page) + 1)
                        }, function (data) {
                            Controller.api.renderRecord(data.message, data.sessionInfo, data.pageData)
                            Config.pageData = data.pageData;
                            return false;
                        })
                    }
                }
            });

            // 图片预览
            $(document).on('dblclick', '.record-img', function (event) {
                var e = $(event.currentTarget),
                    src = e.attr('src');

                layer.photos({
                    photos: {
                        "title": "聊天图片预览",
                        "id": "record",
                        data: [
                            {
                                "src": src
                            }
                        ]
                    },
                    end: function () {

                    }, anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
                });
            });
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            renderRecord: function (message, sessionInfo, pageData) {
                if (sessionInfo.windowType == 'message') {

                    var messageTemplate = FastIm.template.message()
                    var recordsEL = $('.chat-records')

                    if (parseInt(pageData.page) == 1) {
                        $('.chat-records').show()
                        $('.chat-records').empty()
                    }

                    if (message.length) {
                        for (var i = 0; i < message.length; i++) {
                            recordsEL.append('<li class="chat-record-item system"><span>' + message[i].datetime + '</span></li>');
                            for (var y = 0; y < message[i].data.length; y++) {
                                var pushUser = {} // 消息上需要的用户数据
                                if (message[i].data[y].type == 'system') {
                                    var newHTML = '<li class="chat-record-item system"><span>' + message[i].data[y].message.message + '</span></li>';
                                } else {
                                    message[i].data[y].message = FastIm.build.message(message[i].data[y])
                                    if (sessionInfo.type == "group") {

                                        // 群聊消息
                                        if (message[i].data[y].sender_id == sessionInfo.user.id) {
                                            pushUser.hidden_nickname = 'fastim-hidden'
                                            message[i].data[y].record_content_before = 'record_content_before'

                                            if (message[i].data[y].read_number >= (sessionInfo.sessionUser.user_count - 1)) {
                                                message[i].data[y].status = FastIm.common.messageStatus(6, message[i].data[y].id);
                                            } else if (message[i].data[y].read_number > 0) {
                                                message[i].data[y].status = FastIm.common.messageStatus(5, message[i].data[y].id, false, message[i].data[y].read_number)
                                            } else {
                                                message[i].data[y].status = FastIm.common.messageStatus(message[i].data[y].status, message[i].data[y].id)
                                            }
                                        }

                                        pushUser.id = message[i].data[y].userInfo.id
                                        pushUser.nickname = message[i].data[y].userInfo.nickname
                                        pushUser.avatar = FastIm.common.imgUrl(message[i].data[y].userInfo.avatar)
                                    }

                                    var newHTML = messageTemplate({
                                        messageData: message[i].data[y],
                                        sessionInfo: {
                                            pushUser: pushUser
                                        }
                                    });
                                }
                                recordsEL.append(newHTML)
                            }
                        }
                    } else if (parseInt(pageData.page) <= 1) {
                        recordsEL.append('<div class="fastim-data-none">暂时没有聊天记录~</div>');
                    }
                }
            }
        }
    };
    return Controller;
});